package com.server.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.server.password.MyMD5;
import com.server.service.IMngLoginService;

@Service("MngLoginService")
public class MngLoginService implements IMngLoginService{

	@Autowired 
	private JdbcTemplate jdbcTemplate;
	
	
	@Override
	public Map<String, Object> login(String username, String password) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		Boolean isSuccess = false;
		String nickname = null;
		Boolean valid = false;
		String authority = null;
		String uuid = null;
		String encryptStr = MyMD5.circularlyEncrypt(password, 3);
		String sql = "select au.nickname,au.valid,au.uuid,ar.authority from education.admin_user au join education.admin_role  ar on au.role_id=ar.id  where (nickname='%s' or mobile_phone='%s') and password = '%s'";
		List <Map<String,Object>> list = jdbcTemplate.queryForList(String.format(sql, username,username,encryptStr));
		if (list.size()>0) {
			Map<String, Object> map = list.get(0);
			Object nameObj = map.get("nickname");
			if (nameObj != null) {
				nickname = nameObj.toString();
			}
			valid = (Boolean) map.get("valid");
			Object authorityObj = map.get("authority");
			if (authorityObj != null) {
				authority = authorityObj.toString();
			}
			Object uuidObj = map.get("uuid");
			if (uuidObj != null) {
				uuid = uuidObj.toString();
			}
			isSuccess = true;
		}
		returnMap.put("isSuccess", isSuccess);
		returnMap.put("valid", valid);
		returnMap.put("nickname", nickname);
		returnMap.put("authority", authority);
		returnMap.put("uuid", uuid);
		return returnMap;
		
	}


	@Override
	public Boolean updatePassword(String password,String uuid) {
		Boolean isSuccess = false;
		String encryptStr = MyMD5.circularlyEncrypt(password, 3);
		String sql = "update education.admin_user set password='%s' where uuid='%s'";
		try {
			int id = jdbcTemplate.update(String.format(sql, encryptStr,uuid));
			if(id>0){
				isSuccess = true;
			}else{
				isSuccess = false;
			}
		} catch (Exception e) {
			isSuccess = false;
		}
		
		return isSuccess;
	}

}
